import { CodeEditor } from "../CodeEditor"
import { useEffect, useState } from "react"
import { useComponentStore } from "../../../editor/stores/components"

export interface CustomJSConfig {
    type: "customJs"
    code: string
}

export interface CustomJSProps {
    value?: string
    defaultValue?: string
    onChange?: (config: CustomJSConfig) => void
}

// 接收 CustomJSProps 返回 CustomJSConfig
export function CustomJS(props: CustomJSProps){
    const { value: val, defaultValue, onChange } = props

    const { curComponentId } = useComponentStore()
    const [value, setValue] = useState(defaultValue || "")

    useEffect(() => {
        if (val) {
            setValue(val)
        }
    }, [val])

    function codeChange(value: string = ""){
        if (!curComponentId) return

        setValue(value)

        onChange && onChange({
            type: "customJs",
            code: value
        })
    }

    return (
        <div className="mt-[40px]">
            <div className="flex items-start gap-[20px]">
                <div>自定义 JS</div>
                <div className="customJs">
                    <CodeEditor 
                        width="600px"
                        height="400px"
                        value={value} 
                        onChange={codeChange} 
                        defaultOptions={{ languages: 'js', path: 'action.js'}
                    } />
                </div>
            </div>
        </div>

    )

}